package com.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ReceiveAction extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(ReceiveAction.class);


    private EsServiceImpl esService;

    private Map<String, Keys> keys;

    private ThreadPoolExecutor threadService;

    private long rejectedCount = 0;

    private ReceiveAction() {
        super();
    }

    public void init() throws ServletException {
        super.init();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        esService = context.getBean(EsServiceImpl.class);
        loadKeys();
        //后台执行上传任务
        threadService = new ThreadPoolExecutor(200, 800, 30000L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(3000),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        rejectedCount++;
                        logger.error("upload Task rejected from " +
                                executor.toString() + "rejectedCount:" + rejectedCount);
                    }
                });
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        if (request.getParameter("loadkey") != null) {
            loadKeys();
            response.getWriter().append("ok:" + keys.size());
            return;
        } else if (request.getParameter("statistic") != null) {
            String stat = esService.getStatistic();
            response.getWriter().append(stat + "拒绝数： " + rejectedCount
                    + "线程池状态：" + threadService);
            return;
        }
        final String type = request.getParameter("type");
        final String data = new String(request.getParameter("data")
                .getBytes("ISO-8859-1"), "utf-8");

        threadService.execute(new Runnable() {
            @Override
            public void run() {
                esService.pubData(data,type);
            }
        });
        response.getWriter().append("ok");
    }

    public void loadKeys(){
        keys.put("root",new Keys());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
